package com.xhwy.controller;

import com.xhwy.entity.Product;
import com.xhwy.param.ProductParam;
import com.xhwy.param.ProductIdParam;
import com.xhwy.param.ProductQueryParam;
import com.xhwy.service.ProductService;
import com.xhwy.util.PageUtil;
import com.xhwy.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping
    public PageUtil<Product> queryAllByLimit(Product product, PageUtil<Product> pageUtil){
        return productService.queryAllByLimit(product, pageUtil);
    }

    @DeleteMapping("/{productId}")
    public R deleteProductById(@PathVariable Integer productId){
        return productService.deleteProductById(productId);
    }

    @PostMapping
    public R addProduct(@RequestBody @Validated ProductParam product, BindingResult result){
        if (result.hasErrors()) return R.fail("请求参数异常!");
        System.out.println(product);
        return productService.addProduct(product);
    }

    /**
     * 获取推荐列表
     * @return
     */
    @GetMapping("getRecommendList")
    public R getRecommendList(){
        return productService.getRecommendList();
    }

    /**
     * 获取热销商品列表
     * @return
     */
    @GetMapping("getHotProductList")
    public R getHotProductList(){
        return productService.getHotProductList();
    }

    @GetMapping("getByProductType")
    public R getByProductType(@Validated ProductQueryParam productQueryParam, BindingResult result){
        System.out.println(productQueryParam.toString());
        if (result.hasErrors()){
            return R.fail("查询参数错误");
        }
        return productService.getByProductType(productQueryParam);
    }

    @GetMapping("/detail")
    public R detail(@Validated ProductIdParam productIdParam, BindingResult result){
        if (result.hasErrors()){
            return R.fail("参数异常，查询详情失败");
        }
        return productService.detail(productIdParam);
    }
    //开启/关闭推荐
    @PutMapping("/recommend")
    public R recommend(@RequestBody @Validated ProductIdParam productIdParam, BindingResult result){
        if(result.hasErrors()) return R.fail("请求参数异常!");
        return productService.recommend(productIdParam);
    }
    //上架/下架商品
    @PutMapping("/changeSellState")
    public R changeSellState(@RequestBody @Validated ProductIdParam productIdParam, BindingResult result){
        if(result.hasErrors()) return R.fail("请求参数异常!");
        return productService.changeSellState(productIdParam);
    }
}
